package threadPool;

import java.util.concurrent.*;

public class ScheduledThreadPoolTest {
    public static void main(String[] args) throws InterruptedException {
        //test1();
        //test2();
        test3();
    }

    public static void test1() throws InterruptedException {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        for (int i = 0; i < 10; i++) {
            final int index = i;
            scheduledThreadPool.schedule(() -> {
                System.out.println(Thread.currentThread().getName() + ">> delay" +
                        +index + " seconds run ...");
            }, index, TimeUnit.SECONDS);
        }
        scheduledThreadPool.shutdown();
    }

    public static void test2() throws InterruptedException {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(12);
        scheduledThreadPool.scheduleAtFixedRate(() -> {
            System.out.println(Thread.currentThread().getName() + ">> delay" +
                    +System.currentTimeMillis());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ">> run..." + System.currentTimeMillis());
        }, 0, 2, TimeUnit.SECONDS);

    }
    public static void test3() throws InterruptedException {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);
        ScheduledFuture<?> scheduleWithFixedDelay =  scheduledThreadPool.scheduleWithFixedDelay(() -> {
            System.out.println(Thread.currentThread().getName() + ">> delay" +
                    +System.currentTimeMillis());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ">> run..." + System.currentTimeMillis());
        }, 0, 1, TimeUnit.SECONDS);
        Thread.sleep(10000);
        scheduleWithFixedDelay.cancel(true);
        scheduledThreadPool.shutdown();
    }
}
